package com.yunti.springboot.config.component;

import com.yunti.springboot.bo.UserBO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Function;


/**
 * @author yxp
 */
@Component
public abstract class AbstractCurrentRequestComponent {
    public static final String TOKEN_KEY = "loginToken_";

    public static final String M_OA_KEY = "APPTOKEN_";

    public static final String REQUEST_HEADER_TOKEN = "Authorization";
    public static final String UNKNOWN="unknown";
    public static final String REQUEST_HEADER_XTENANT = "xtenant";

    @Resource
    protected StringRedisTemplate stringRedisTemplate;

    /**
     * 获取当前登陆用户信息
     *
     * @return 当前登录用户信息
     */
    public abstract UserBO getCurrentStaffId();

    /**
     * 模拟用户信息,非http请求使用
     * @param user
     * @param callback
     * @param <R>
     * @return
     */
    public abstract <R> R invokeWithUser(UserBO user, Function<UserBO,R> callback);

    public String getCurrentIp() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = StringUtils.split(ip, ",");
        if (ips != null && ips.length > 1) {
            ip = ips[0];
        }
        return ip;
    }
}
